package com.hj.security.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hj.security.provider.AppLockProvider;
import com.hj.security.utils.DBHelper;

public class AppLockDao {

	private DBHelper dbHelper;
	private Context context;

	public AppLockDao(Context context) {
		dbHelper = new DBHelper(context);
		this.context = context;
	}
	
	public boolean find(String packageName){
		boolean result = false;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		if(db.isOpen()){
			Cursor cursor = db.rawQuery("select packagename from applock where packagename=?", new String[]{packageName});
			if(cursor.moveToNext()){
				result = true;
			}
			cursor.close();
			db.close();
		}
		return result;
	}
	public void add(String packageName){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if(db.isOpen()){
			db.execSQL("insert into applock(packagename) values(?)",new Object[]{packageName});
			context.getContentResolver().notifyChange(AppLockProvider.URI, null);
		}
	}
	public void delete(String packageName){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if(db.isOpen()){
			db.execSQL("delete from applock where packagename=?",new Object[]{packageName});
			context.getContentResolver().notifyChange(AppLockProvider.URI, null);
		}		
	}
	public List<String> getAllPackageName(){
		List<String> packageNames = new ArrayList<String>();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		if(db.isOpen()){
			Cursor cursor = db.rawQuery("select packagename from applock", null);
			while(cursor.moveToNext()){
				packageNames.add(cursor.getString(0));
			}
			cursor.close();
			db.close();
		}
		return packageNames;
	}
}
